package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"regi-sys/cache"
	"regi-sys/model"
	"time"

	"regi-sys/userrpc/internal/svc"
	"regi-sys/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserDetailLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserDetailLogic {
	return &UserDetailLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户查询
func (l *UserDetailLogic) UserDetail(in *userrpc.UserDetailRequest) (*userrpc.UserDetailResponse, error) {
	// todo: add your logic here and delete this line

	var user model.User
	key := fmt.Sprintf("user_detail_%s", in.Account)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cacheData == "" {
		err := user.UserDetailByAccount(model.DB, in.Account)
		if err != nil {
			return nil, errors.New("用户不存在,查询失败")
		}
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*3)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}

	return &userrpc.UserDetailResponse{
		UserId:   int64(user.ID),
		Account:  user.Account,
		Password: user.Password,
	}, nil
}
